#include "ProfilerWidget.h"
#include <SEUi/SEUi.h>
#include <SEDebug/Log/Log.h>

namespace SEngine
{    
    ProfilerWidget::ProfilerWidget(EditLayer & layer)
        : m_layer(layer)
    {
        // m_timer.Run(1000, [this]() {
        //     m_fps = 1000 / (m_delta == 0 ? 1 : m_delta);
        // }, false);
    }

    void ProfilerWidget::OnCameraUpdate(Camera &camera)
    {
        SignalUpdateGUI.AddSlot([&camera]() {
            ImGui::Text("Camera Position: %.2f %.2f %.2f", camera.GetPos().x, camera.GetPos().y, camera.GetPos().z);
            ImGui::Text("Camera zNear: %.2f", camera.GetZNear());
            ImGui::Text("Camera zFar: %.2f", camera.GetZFar());
            return SlotState::Once;
        });
    }

    void ProfilerWidget::OnCameraSpeedUpdate(float speed)
    {
        SignalUpdateGUI.AddSlot([&speed]() {
            ImGui::Text("Camera Speed: %.2f", speed);
            return SlotState::Once;
        });
    }

    void ProfilerWidget::UpdateImpl(int delta)
    {
        ImGui::Text("FPS: ");
        ImGui::SameLine();
        float fps =  1000.0f / (delta == 0 ? 1 : delta);
        float avg = 0.0f;
        for (int i = 0; i < TIME_RECORD_COUNT; ++i) {
            avg += m_fpsRecord[i];
        }
        avg /= (float)TIME_RECORD_COUNT;
        m_fpsRecord[m_curFpsOffset] = fps;
        ImGui::PlotLines("##FPS", m_fpsRecord, IM_ARRAYSIZE(m_fpsRecord), m_curFpsOffset, ("avg: " + std::to_string(avg)).c_str(), 
            0.0f, 120.0f, ImVec2{200, 100}, sizeof(float));
        SignalUpdateGUI.Invoke();
        m_curFpsOffset = (m_curFpsOffset + 1) % TIME_RECORD_COUNT;
    }
} // namespace SEngine
